let objPath = document.getElementById("path");
let objPayload = document.getElementById("payload");
let objCurrentServerStatus = document.getElementById("serverStatus");
let objOnlineCounter = document.getElementById("online");
let objOnlineList = document.getElementById("onlineList");
let objMusicanotes = document.getElementById("musicanotes");

let lastMessageId = document.getElementById("LMId").innerText;
let reqIsFailed = false;
let firstLoadingWithDisconnectedServer = false;
let unreadedCount = 0;
let soundEnabled = false;

const ajaxUrl = document.getElementById("ajaxPath").innerText;
const originalTitle = document.title;
const audio = new Audio('/newmessage.mp3');
const HTML_SERVER_ONLINE_MARKER = "✅";
const HTML_SERVER_OFFLINE_MARKER = "❌";

function sound() {
    if (!soundEnabled) {
        soundEnabled = true;
        objMusicanotes.style.opacity = "1";
        objMusicanotes.title = "Sound notifications enabled";
    } else {
        soundEnabled = false;
        objMusicanotes.style.opacity = ".3";
        objMusicanotes.title = "Sound notifications disabled";
    }
}

function appendMessage(nick /* if == "***", then system message */, message)
{
    let messageObject = document.createElement("div");
    messageObject.setAttribute("class", "main_payload__chat");
    const date = new Date;
    messageObject.setAttribute("title", date.toLocaleString());

    let nicknameContainer = document.createElement("div");
    nicknameContainer.setAttribute("class", "main_payload__chat_username");
    if (nick === "***") {
        nicknameContainer.setAttribute("style", "color: white; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;");
        nicknameContainer.innerText = "IRCaBot";
    } else {
        nicknameContainer.innerText = nick;
        nicknameContainer.setAttribute("style", "color: #1b4af5");
        if (document.hidden) {
            unreadedCount++;
            document.title = '(' + unreadedCount + ') ' + originalTitle;
            if (soundEnabled) {
                audio.play();
            }
        }
    }

    let textContainer = document.createElement("div");
    textContainer.setAttribute("class", "main_payload__chat_mail");
    textContainer.innerHTML = message;

    messageObject.appendChild(nicknameContainer);
    messageObject.appendChild(textContainer);
    objPayload.appendChild(messageObject);
    objPayload.scrollBy(0,1000);
}

function changeOnlineList(nicksArray)
{
    objOnlineList.innerHTML = "";
    nicksArray.forEach(function(nick) {
        let nickObject = document.createElement("div");
        nickObject.setAttribute("class", "main_middle__online_point");
        nickObject.innerText = nick;
        objOnlineList.appendChild(nickObject);
    });
}

function toAJAX()
{
    loop();
    let xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
        if (reqIsFailed) {
            reqIsFailed = false;
            objPath.removeAttribute("style");
        }
        const answer = JSON.parse(xhttp.responseText);
        if (firstLoadingWithDisconnectedServer && answer.serverStatus) {
            firstLoadingWithDisconnectedServer = false;
            appendMessage("***", "<b>Connected to the server</b>. New messages will appear below!");
            objPath.removeAttribute("style");
        }
        if (!answer.status) {
            appendMessage("***", answer.message);
            return;
        }
        if (answer.serverStatusChanged) {
            if (answer.serverStatus) {
                objPath.removeAttribute("style");
                objCurrentServerStatus.innerText = HTML_SERVER_ONLINE_MARKER;
            } else {
                objPath.setAttribute("style", "color: red");
                objCurrentServerStatus.innerText = HTML_SERVER_OFFLINE_MARKER;
            }
        }
        if (answer.onlineUsersChanged) {
            const onlineInfo = answer.online;
            objOnlineCounter.innerText = onlineInfo.count;
            changeOnlineList(onlineInfo.list);
        }
        if (answer.LMIdChanged) {
            lastMessageId = answer.LMId;
            let msgArray = answer.newMessages;
            msgArray.forEach(function(singleMsg) {
                appendMessage(singleMsg.user, singleMsg.text);
            });
        }
        setTimeout(toAJAX, 2000); // 2 sec
    }
    xhttp.onerror = function() {
        if (!reqIsFailed) {
            reqIsFailed = true;
            objPath.setAttribute("style", "color: red");
        }
        setTimeout(toAJAX, 1000); // 1 sec
    }

    let currentServerStatus = objCurrentServerStatus.innerText === HTML_SERVER_ONLINE_MARKER;
    xhttp.open("GET", "/ajax/"+ajaxUrl+"?onlineCounter="+objOnlineCounter.innerText+"&messageId="+lastMessageId+"&serverStatus="+currentServerStatus);
    xhttp.send();
}

function loop()
{
    if (!document.hidden && unreadedCount>0) {
        unreadedCount = 0;
        document.title = originalTitle;
    }
    let dots = objPath.innerText;
    if (dots === "...") {
        dots = ""
    } else {
        dots += ".";
    }
    objPath.innerText = dots;
}

function main()
{
    sound();
    objPayload.scrollBy(0,100000);
    let objHr = document.getElementById("hr");
    if (objCurrentServerStatus.innerText === HTML_SERVER_OFFLINE_MARKER) {
        firstLoadingWithDisconnectedServer = true;
        objPath.setAttribute("style", "color: red");
        hr.innerHTML = "Now the logger is disconnected from the server, so there will be no new messages.";
    } else {
        hr.innerHTML = "<b>New messages will appear below<b>";
    }

    toAJAX();
}

main();
